package service

import (
	"fmt"
	"gin-luban-server/global"
	"gin-luban-server/model"
	"strings"
	"time"
)

// 所有部署任务集合
func AllCron()  {
	// 部署任务
	go deployTimeoutFunc()
	go RedisMonitor()
}


// 部署超时函数
func deployTimeoutFunc() {
	var ch chan int
	deployTimeout := global.GVA_CONFIG.Deploy.Timeout
	ticker := time.NewTicker(time.Second * time.Duration(deployTimeout))
	go func() {
		for range ticker.C {
			nowTimeStamp := time.Now().Unix() // 当前时间
			fmt.Println("定时监控部署超时信息:", time.Now().Format("2006-01-02 15:04:05"))
			var buildInfo []model.DeployBuildHistory
			// 将运行中 超过timeout时间的 状态置为4
			global.GVA_DB.Debug().Where("(? -unix_timestamp(created_at)) < ? AND (? - unix_timestamp(created_at)) > ? AND deploy_status = 1" ,nowTimeStamp,deployTimeout * 2 ,nowTimeStamp,deployTimeout).Find(&buildInfo)
			for _, build := range buildInfo {
				// 更新数据库状态 为超时状态
				excludeJobs := global.GVA_CONFIG.Deploy.ExcludeTimeoutJobs
				if len(excludeJobs) >= 1 {
					for _, excludeJob := range excludeJobs {
						if !strings.Contains(build.AppsJobName, excludeJob) {
							build.DeployStatus = "4"
							global.GVA_DB.Save(&build)
							global.GVA_LOG.Info( build.AppsJobName + "JOB部署超时")
						}
					}
				} else {
					build.DeployStatus = "4"
					global.GVA_DB.Save(&build)
					global.GVA_LOG.Info( build.AppsJobName + "JOB部署超时")
				}

			}

		}
		ch <- 1
	}()
	<-ch
}